import { setSysDic, getSysDic, setFileModel, getFileModel, setFileChildModel, getFileChildModel} from '@/utils/localStorageData'
import api from '@/api'
const state = {
  sysDic: getSysDic(),
  fileModel: getFileModel(),
  fileChildModel: getFileChildModel(),
}

const mutations = {
  SET_SYS_DIC: (state, data) => {
    state.sysDic = data
  },
  SET_FILE_MODEL: (state, data) => {
    state.fileModel = data
  },
  SET_FILE_MODEL_CHILD: (state, data) => {
    state.fileChildModel = data
  },
}

const actions = {
  getFileSource({ commit, state }) {
    return new Promise((resolve, reject) => {
      api.PROJECT_START_FILE_TYPE().then(response => {
        if (response.code === 200) {
          const { data } = response
          if (data){
            let model = {}
            let child = {}
            data.forEach(item=>{
              model[item.Key] = item.Value

              if (item.Children){
                item.Children.forEach(a=>{
                  child[a.Key] = a.Value
                  model[a.Key] = a.Value
                })
              }
            })
            commit('SET_FILE_MODEL', data)
            commit('SET_FILE_MODEL_CHILD', model)
            setFileModel(data)
            setFileChildModel(model)
          }

          resolve(data)
        } else {
          reject(response.msg)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  getSysAllDic({ commit, state }) {
    return new Promise((resolve, reject) => {
      api.PROJECT_SYS_ALLDICT_LIST().then(response => {
        if (response.code === 200) {
          const { data } = response
          commit('SET_SYS_DIC', data)
          setSysDic(data)
          resolve(data)
        } else {
          reject(response.msg)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  getSysDic({ commit, state }, str) {
    return new Promise((resolve, reject) => {
      api.PROJECT_SYS_ALLDICT_LIST().then(response => {
        if (response.code === 200) {
          const { data } = response
          commit('SET_SYS_DIC', data)
          setSysDic(data)
          let list = null
          if (data && str) {
            list = data[str]
          }
          resolve(list)
        } else {
          reject(response.msg)
        }
      }).catch(error => {
        reject(error)
      })
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
